﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Data;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Data.OleDb;

namespace BSC_OTC_Management.Code
{
    class CL_Ultility
    {

        #region "KHAI BAO BIEN TOAN CUC" 
        Code.StaticVariable _code = new StaticVariable();
        public  Hashtable v_HtbCompanyLIst = new Hashtable();  
        public  Hashtable v_HtbSubfund = new Hashtable();
        public  Hashtable v_HtbSymbol = new Hashtable();
        public  DataTable v_dtbSymbolInfo;
        public   string v_strTatCa = "Tất cả";
        public BSC_SERVICES.Service1SoapClient _services = new BSC_SERVICES.Service1SoapClient();
        Hashtable v_HtbLIst = new Hashtable();
        //DataAccess v_obj;
        static bool Bool_PlaceOrder = false;
        

        public Boolean Get_PlaceOrder_Status
        {
            get { return Bool_PlaceOrder; }
            set { Bool_PlaceOrder = value; }
        }
        #endregion

        #region "CAC HAM DUNG CHUNG"

        // ham nay de tra ve authcode 

        public bool IsNumeric(string s)
        {
            float output;
            return float.TryParse(s, out output);
        }

        public bool IsNumericAndLarger1000(string s)
        {
            try
            {
                double output = Convert.ToDouble(s);
                if (output >= 1000)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;   
            }
            return false;
        }
        
        public string GetAuthCodeMenuid(string _menuID)
        {
            foreach (DataRow  row in Code.StaticVariable.tablePermission.Rows)
            {
                if (Convert.ToString(row["menuid"]) == _menuID)
                {
                    return Convert.ToString(row["authcode"]);
                }
            }
            return "";
        }

        // Ham nay de chay 1 file bat ky trong may tinh
        public void RunFile(string _filename)
        {
            try
            {
                System.Diagnostics.Process.Start(_filename);
            }
            catch (Exception ex )
            {
                MessageBox.Show("lỗi khi mở file " + _filename + " : " + ex.Message);
            }
            
        }

        //chọn file return filename
        public string OpenFileDialog_ReturnFileName()
        {
            string path = "";
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Title = "Chọn File";
                openFileDialog.Filter = "Excel files|*.xls;*.xlsx";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    path = openFileDialog.FileName;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return path;
        }

        //Read file excel return datatable
        public DataTable CreateDataTableForExcelData(String filePath)
        {
            OleDbConnection ExcelConnection = null;
            DataTable dtNew = new DataTable();
            string sheetName = "";
            try
            {
                ExcelConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;");

                ExcelConnection.Open();
                DataTable dt = ExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                sheetName = dt.Rows[0]["TABLE_NAME"].ToString();
                OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM [" + sheetName + @"]", ExcelConnection);
                OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
                DataSet ExcelDataSet = new DataSet();
                ExcelAdapter.Fill(dtNew);
                ExcelConnection.Close();

            }
            catch (Exception ex)
            {
                ExcelConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;");
                ExcelConnection.Open();
                DataTable dt = ExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                sheetName = dt.Rows[0]["TABLE_NAME"].ToString();
                OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM [" + sheetName + @"]", ExcelConnection);
                OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
                DataSet ExcelDataSet = new DataSet();
                ExcelAdapter.Fill(dtNew);
                ExcelConnection.Close();
            }

            return dtNew;
        }

        public string Set_value_to_Combobox(DataTable v_TBL, ComboBox cbb_name, string Collum_name, string v_strDK)
        {
            try
            {
                DataView dv = new DataView(v_TBL);
                dv.RowFilter = v_strDK;
                DataTable dbt_temp = new DataTable();
                dbt_temp = dv.ToTable();
                cbb_name.Items.Clear();
                //cbb_name.Items.Add("Tất cả");
                int l = dbt_temp.Rows.Count;
                for (int i = 0; i < l; i++)
                {
                    string v_item = dbt_temp.Rows[i][Collum_name].ToString();
                    if (cbb_name.Items.Contains(v_item) != true)
                    {
                        cbb_name.Items.Add(dbt_temp.Rows[i][Collum_name].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }

        public string LAY_THONG_TIN_LOI_TU_MA_LOI(string v_ErrNum)
        {
            try
            {
                string v_Cmd = @"Select errdesc From deferror where errnum ='" + v_ErrNum + "'";
                return _code._services.GetDatatable_BySQL(v_Cmd).Rows[0][0].ToString();
            }
            catch { }
            return "Lỗi không xác định";
        }

        public string Get_key_HashTable(Hashtable v_HashTable, String v_InValues)
        {
            try
            {
                foreach (DictionaryEntry item in v_HashTable)
                {
                    string v_dk1  = item.Value.ToString().Trim() ;
                    string v_dk2 = v_InValues.Trim();
                    if ( v_dk1==v_dk2 )
                    {
                        return item.Key.ToString();
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            using (var ms = new MemoryStream())
            {
                imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Close();
                return ms.ToArray();
            }
        }

        public Image ByteToImage(byte[] blob)
        {
            MemoryStream mStream = new MemoryStream(blob);
            return Bitmap.FromStream(mStream);
        }

        public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to base 64 string
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

        public string Get_value_HashTable(Hashtable v_HashTable, String v_InKey)
        {
            try
            {
                foreach (DictionaryEntry item in v_HashTable)
                {
                    if (item.Key.ToString() == v_InKey.Trim())
                    {
                        return item.Value.ToString();
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        public string FILL_HashTable(Hashtable v_HashTable, DataTable v_DataTable, ComboBox v_CbbName , string v_KeyOrValue)
        {
            try
            {
                v_HashTable.Clear();
                v_HashTable.Add("ALL", v_strTatCa);
                if (v_CbbName != null )
                {

                    v_CbbName.Items.Clear();
                    if (v_CbbName.Name != "cbb_Company_Name")
                    {
                        v_CbbName.Items.Add(v_strTatCa);
                        v_CbbName.Text = v_strTatCa;
                    }

                }

                foreach (DataRow row in v_DataTable.Rows)
                {
                    v_HashTable.Add(row["KeyName"].ToString(), row["KeyValue"].ToString());

                    if (v_CbbName != null)
                    {
                        if (v_KeyOrValue == "KEY")
                        {
                            v_CbbName.Items.Add(row["KeyName"].ToString());
                        }
                        else
                        {
                            v_CbbName.Items.Add(row["KeyValue"].ToString());
                        }                        
                    }
                }

                if (v_CbbName.Name == "cbb_Company_Name")
                {
                    v_CbbName.Text = v_CbbName.Items[0].ToString();
                }
            }
            catch
            { }
            return null;
        }

        public void Log_event(string s_function, string sEvent)
        {
            try
            {
                string sSource = null;
                string sLog = null;
                string sMachine = null;
                sSource = "WebDBConnect - " + s_function;
                sLog = "Application";
                sMachine = ".";
                EventLog ELog = new EventLog(sLog, sMachine, sSource);
                ELog.WriteEntry(sEvent, EventLogEntryType.Error, 234, Convert.ToInt16(3));
            }
            catch (Exception ex)
            {
                string sSource = null;
                string sLog = null;
                string sMachine = null;
                sSource = "WebDBConnect - " + s_function;
                sLog = "Application";
                sMachine = ".";
                EventLog ELog = new EventLog(sLog, sMachine, sSource);
                ELog.WriteEntry(ex.Message, EventLogEntryType.Error, 234);
            }
        }

        public string So_chuan(double so)
        {
            try
            {
                string so1 = "";
                if (so < 10)
                {
                    so1 = "0" + so.ToString();
                }
                else
                {
                    so1 = so.ToString();
                }
                return so1.ToString();
            }
            catch (Exception ex)
            {
                this.Log_event("So_chuan", ex.Message);
                return "";
            }

        }

        public string Bon_So_chuan(string so)
        {
            string kq = "";
            try
            {
                int l = so.Length;
                switch (l)
                {
                    case 1:
                        kq = "000" + so.ToString();
                        break;
                    case 2:
                        kq = "00" + so.ToString();
                        break;
                    case 3:
                        kq = "0" + so.ToString();
                        break;
                    case 4:
                        kq = so.ToString();
                        break;
                }
                return kq.ToString();
            }
            catch (Exception ex)
            {
                Log_event("Bon_So_chuan", ex.Message);
                return "";
            }
        }


        
        public string Current_DATE(string Date_type)
        {
            DateTime dt = System.DateTime.Now;
            string F_Time = dt.ToShortDateString();
            try
            {
                switch (Date_type.ToLower())
                {
                    case "yyyy_mm_dd":
                        F_Time = So_chuan(dt.Year).ToString() + "_" + So_chuan(dt.Month).ToString() + "_" + So_chuan(dt.Day).ToString();
                        break;
                    case "yyyymmdd":
                        F_Time = So_chuan(dt.Year).ToString() + So_chuan(dt.Month).ToString() + So_chuan(dt.Day).ToString();
                        break;
                    case "dd/mm/yyyy hh:pp:ss":
                        F_Time = So_chuan(dt.Day).ToString() + "/" + So_chuan(dt.Month).ToString() + "/" + So_chuan(dt.Year).ToString() + " " + So_chuan(dt.Hour).ToString() + ":" + So_chuan(dt.Minute).ToString() + ":" + So_chuan(dt.Second).ToString();
                        break;
                    case "hh:mm:ss:ms":
                        F_Time = So_chuan(dt.Hour).ToString() + ":" + So_chuan(dt.Minute).ToString() + ":" + So_chuan(dt.Second).ToString() + ":" + Bon_So_chuan(dt.Millisecond.ToString()).ToString();
                        break;
                    //case "HH:mm:ss":
                    case "hh:mm:ss":
                        F_Time = So_chuan(dt.Hour).ToString() + ":" + So_chuan(dt.Minute).ToString() + ":" + So_chuan(dt.Second).ToString();
                        break;
                    //case "dd/MM/yyyy":
                    case "dd/mm/yyyy":
                        F_Time = So_chuan(dt.Day).ToString() + "/" + So_chuan(dt.Month).ToString() + "/" + So_chuan(dt.Year).ToString();
                        break;
                }
                return F_Time;
            }
            catch (Exception ex)
            {
                Log_event("Current_DATE", ex.Message);
                return "";
            }
        }

        public void ClearAllText(Control con)
        {
            foreach (Control c in con.Controls)
            {
                if (c is TextBox)
                    ((TextBox)c).Clear();
                else
                    ClearAllText(c);
            }
        }

        // hàm này convert từ Byte[] -- > file ( mẫu sổ Trái chủ) 
        public bool SaveDocument(Byte[] docbinaryarray, string _document)
        {
            FileStream objfilestream = new FileStream(_document, FileMode.Create, FileAccess.ReadWrite);
            objfilestream.Write(docbinaryarray, 0, docbinaryarray.Length);
            objfilestream.Close();

            return true;
        }

        // hàm này convert từ File --> byte[]
        public Byte[] GetDocument(string _document)
        {
            FileStream objfilestream = new FileStream(_document, FileMode.Open, FileAccess.Read);
            int len = (int)objfilestream.Length;
            Byte[] documentcontents = new Byte[len];
            objfilestream.Read(documentcontents, 0, len);
            objfilestream.Close();
            return documentcontents;
        } 

        //hàm này định dạng số 10000 --> 10,000
        public string NumberFormat(string _str)
        {
            try
            {
                if (_str.Length > 0)
                {
                    double temp = Convert.ToDouble(_str);
                    return String.Format("{0:#,##0.###}", temp);
                }
                else
                {
                    return _str;
                }
            }
            catch (Exception ex)
            {
                return "Lỗi:" + " bạn phải nhập số";
            }
        }

        public bool CheckDateTime(string datetime)
        {
            bool b = true;
            try
            {
                DateTime d = DateTime.ParseExact(datetime, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                b = true;
            }
            catch(Exception ex){
                ex.ToString();
                b = false;
            }
            return b;
        }

        #endregion
    }
}
